<template>
  <div class="app-container">

    <el-form ref="article1" :model="article" :rules="validateRules1">
      <el-row :gutter="20">
        <el-col :span="18">
          <el-form-item prop="title">
            <el-input
              v-model="article.title"
              type="text"
              placeholder="请输入文章标题（5~30个字）"
              maxlength="30"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="3" style="text-align: center">
          <el-button v-if="article.status === 0" :disabled="btnDisabled" type="success" round @click="saveArticle(0)">
            保存草稿
          </el-button>
        </el-col>
        <el-col :span="3" style="text-align: center">
          <el-button :disabled="btnDisabled" type="primary" round @click="saveArticle(1)">发布文章</el-button>
        </el-col>
      </el-row>

      <div class="editor-container">
        <markdown-editor ref="markdownEditor" v-model="article.content" height="800px"/>
      </div>
    </el-form>

    <el-dialog :close-on-click-modal="false" :visible.sync="submitDialogFlag" title="发布文章">
      <el-form ref="article2" :model="article" :rules="validateRules2" label-position="top">
        <el-form-item label="摘要">
          <el-input
            v-model="article.summary"
            :autosize="{ minRows: 3, maxRows: 6}"
            type="textarea"
            placeholder="摘要（选填）：会在推荐、列表等场景外露，帮助读者快速了解内容，如不填写则默认抓取正文前256字符"
            maxlength="256"
            show-word-limit/>
        </el-form-item>
        <el-form-item :rules="validateRules2.tagIds" label="文章标签" prop="tagIds">
          <el-select
            v-model="article.tagIds"
            :multiple-limit="3"
            multiple
            filterable
            clearable
            placeholder="选择1~3个标签"
            style="width: 100%"
            @change="handleSelectChange">
            <el-option
              v-for="item in tags"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="分类专栏">
          <el-select
            v-model="article.channelIds"
            :multiple-limit="3"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择文章标签"
            style="width: 100%"
            @change="handleSelectChange">
            <el-option
              v-for="item in channels"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :disabled="btnDisabled" type="success" @click="publishArticle">确认发布</el-button>
        <el-button type="info" @click="submitDialogFlag = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import MarkdownEditor from '@/components/MarkdownEditor'

import articleApi from '@/api/cms/article'
import tagApi from '@/api/cms/tag'
import channelApi from '@/api/cms/channel'

const titleRule = (rule, value, callback) => {
  if (value.length < 5) {
    callback(new Error('文章标题长度不能小于5位'))
  }
  if (value.length > 30) {
    callback(new Error('文章标题长度不能大于30位'))
  }
  callback()
}

const tagRule = (rule, value, callback) => {
  if (value.length === 0) {
    callback(new Error('请至少选择一个标签'))
  }
  callback()
}

export default {
  name: 'Form',
  components: { MarkdownEditor },
  data() {
    return {
      btnDisabled: false,
      submitDialogFlag: false,
      article: {
        id: '',
        title: '',
        summary: '',
        contentId: '',
        content: '',
        status: 0,
        tagIds: [],
        channelIds: []
      },
      tags: [],
      channels: [],
      validateRules1: {
        title: [
          { required: true, trigger: 'blur', message: '请输入文章标题' },
          { validator: titleRule, trigger: 'blur' }
        ]
      },
      validateRules2: {
        tagIds: [
          { validator: tagRule, trigger: 'change' }
        ]
      }
    }
  },

  created() {
    this.init()
  },

  mounted() {
    window.onbeforeunload = function(e) {
      e = e || window.event
      console.log(e)
      // 兼容IE8和Firefox 4之前的版本
      if (e) {
        e.returnValue = '关闭提示'
      }

      // Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+
      return '关闭提示'
    }
  },

  methods: {

    init() {
      tagApi.getAllTags().then(res => {
        this.tags = res.result
      }).catch(error => {
        console.log(error)
      })

      channelApi.getAllChannels().then(res => {
        this.channels = res.result
      }).catch(error => {
        console.log(error)
      })

      if (this.$route.params && this.$route.params.id) {
        const id = this.$route.params.id
        articleApi.getArticleInfo(id).then(res => {
          this.article = res.result
          this.article.tagIds = res.result.tags.map(tag => tag.id + '')
          this.article.channelIds = res.result.channels.map(channel => channel.id + '')
        }).catch(error => {
          console.log(error)
        })
      }
    },

    saveArticle(val) {
      this.$refs.article1.validate(valid => {
        if (valid) {
          this.article.status = val
          if (this.article.status === 0) {
            this.saveDraft()
          } else {
            this.submitDialogFlag = true
          }
        }
      })
    },

    saveDraft() {
      this.btnDisabled = true
      articleApi.createArticle(this.article).then(res => {
        this.btnDisabled = false
        this.$message({
          type: 'success',
          message: '保存草稿成功'
        })
      }).catch(error => {
        console.log(error)
      })
    },

    publishArticle() {
      this.$refs.article2.validate(valid => {
        if (valid) {
          const content = this.$refs.markdownEditor.getContent()
          if (this.article.summary === '' || this.article.summary.length === 256) {
            if (content.length > 256) {
              this.article.summary = content.substr(0, 256)
            } else {
              this.article.summary = content
            }
          }
          this.btnDisabled = true
          if (this.article.id === '') {
            articleApi.createArticle(this.article).then(res => {
              this.btnDisabled = false
              this.$message({
                type: 'success',
                message: '发布文章成功'
              })
              this.$router.push({ path: '/blog/details/' + res.result })
            }).catch(error => {
              this.btnDisabled = false
              console.log(error)
            })
          } else {
            articleApi.updateArticle(this.article).then(res => {
              this.btnDisabled = false
              this.$message({
                type: 'success',
                message: '发布文章成功'
              })
              this.$router.push({ path: '/blog/details/' + res.result })
            }).catch(error => {
              this.btnDisabled = false
              console.log(error)
            })
          }
        }
      })
    },

    handleSelectChange() {
      this.$forceUpdate()
    }

  }
}
</script>

<style>

.el-tag.el-tag--info {
  background-color: #ecf5ff;
  border-color: #b3d8ff;
  color: #409EFF;
}

.el-tag.el-tag--info .el-tag__close {
  color: #409EFF;
}

.el-select .el-tag__close.el-icon-close {
  background-color: #ecf5ff;
}

</style>
